#!/usr/bin/env python
# -*- coding: utf-8 -*-

__author__ = 'Wu Jin'

from app import db
from datetime import datetime

# i为传入的实例
def _create(i,db=db):
    db.session.add(i)
    db.session.commit()

def _get_query(T):
    return getattr(T,"query",None)

def get_all(T):
    query = _get_query(T)
    return query.filter(getattr(T,"del_flag")==0).all()

def get_by_attr(T,dict):
    query = _get_query(T)
    if dict:
        for key in dict:
            query = query.filter(getattr(T,key)==dict[key])
        return query.first()
    else:
        return None

def get_list_by_attr(T,dict):
    query = _get_query(T)
    if dict:
        for key in dict:
            query = query.filter(getattr(T,key)==dict[key])
        return query.all()
    else:
        return None

def delete(T,id):
    query = _get_query(T)
    if id:
        o = query.filter(getattr(T,"id")==id).one()
        o.del_flag = 1
        db.session.commit()


def _update_column(model, data):
    '''
    自动填充model字段
    model：数据类型 data:数据
    '''
    for (key, value) in data.items():
        if hasattr(model, key):
            setattr(model, key, value)


def create(T,data):
    try:
        model = T()
        _update_column(model,data)
        if hasattr(model, "create_time"):
            model.create_time = datetime.now()
    except BaseException,e:
        return False
    try:
        _create(model,db)
    except BaseException,e:
        return False
    return model

